

import  BaseModel  from '../../genshin/model/db/BaseModel.js'

const { Types } = BaseModel

const COLUMNS = {
  // 用户ID，qq为数字
  ltuid: {
    type: Types.INTEGER,
    primaryKey: true
  },

  // MysUser类型，mys / hoyolab
  type: {
    type: Types.STRING,
    defaultValue: 'fp',
    notNull: true
  },

  device_fp: Types.JSON,
  
  // 是否为手动绑定
  is_manual: {
    type: Types.BOOLEAN,
    defaultValue: false
  }
}

class MysFp extends BaseModel {
  static async find (ltuid = '', create = false) {
    // DB查询
    let mys = await MysFp.findByPk(ltuid)
    if (!mys && create) {
      mys = await MysFp.build({
        ltuid
      })
    }
    return mys || false
  }

  static async findfp (ltuid) {
    // DB查询
    let mys = await MysFp.findByPk(ltuid)
    if(mys) return mys.dataValues.device_fp
    
    // 如果没有找到设备信息，生成默认随机设备信息
    const defaultFp = await MysFp.generateDefaultDeviceFp()
    if (defaultFp) {
      await MysFp.saveDB({
        ltuid: ltuid,
        device_fp: defaultFp,
        is_manual: false
      })
      return defaultFp
    }
    return null
  }

  static async findAllUsers() {
    const users = await MysFp.findAll();
    return users || [];
  }
  
  async saveDB(mys) {
    if (!mys.device_fp) {
      return false
    }
    await MysFp.upsert({
      ltuid: mys.ltuid,
      type: 'fp',
      device_fp: mys.device_fp,
      is_manual: mys.is_manual || false
    },{
      where: {
        ltuid: mys.ltuid
      }
    });
  }

  // 生成默认随机设备指纹
  static async generateDefaultDeviceFp() {
    try {
      const deviceModels = [
        { brand: 'HUAWEI', model: 'DCO-AL00', name: 'HUAWEI DCO-AL00', board: 'dco' },
        { brand: 'Xiaomi', model: 'MI 11', name: 'MI 11', board: 'venus' },
        { brand: 'OPPO', model: 'PEEM00', name: 'OPPO Find X3', board: 'lahaina' },
        { brand: 'vivo', model: 'V2055A', name: 'vivo X60', board: 'lahaina' },
        { brand: 'OnePlus', model: 'LE2100', name: 'OnePlus 9', board: 'lahaina' }
      ]
      
      const randomDevice = deviceModels[Math.floor(Math.random() * deviceModels.length)]
      const oaid = MysFp.generateOaid()
      const deviceGuid = MysFp.getDeviceGuid()
      const seedId = MysFp.getSeed_id()
      
      const fpResponse = await fetch('https://public-data-api.mihoyo.com/device-fp/api/getFp', {
        method: 'post',
        headers: { 
          'Host': 'public-data-api.mihoyo.com',
          'User-Agent': 'okhttp/4.9.3'
        },
        body: JSON.stringify({
          app_name: 'bbs_cn',
          bbs_device_id: deviceGuid,
          device_fp: '38d80737ce6f3',
          device_id: seedId,
          ext_fields: `{"proxyStatus":1,"isRoot":0,"romCapacity":"512","deviceName":"${randomDevice.name}","productName":"${randomDevice.model}","romRemain":"434","hostname":"a11-gz02-test.i.nease.net","screenSize":"1440x2560","isTablet":0,"aaid":"${deviceGuid}","model":"${randomDevice.model}","brand":"${randomDevice.brand}","hardware":"${randomDevice.brand}","deviceType":"${randomDevice.name}","devId":"REL","serialNumber":"unknown","sdCapacity":127991,"buildTime":"1731038709000","buildUser":"builder001","simState":5,"ramRemain":"125933","appUpdateTimeDiff":1741848587885,"deviceInfo":"${randomDevice.brand}/${randomDevice.model}/${randomDevice.name}:12/SKQ1.210216.001/V417IR:user/release-keys","vaid":"${deviceGuid}","buildType":"user","sdkVersion":"32","ui_mode":"UI_MODE_TYPE_NORMAL","isMockLocation":0,"cpuType":"arm64-v8a","isAirMode":0,"ringMode":2,"chargeStatus":1,"manufacturer":"${randomDevice.brand}","emulatorStatus":0,"appMemory":"512","osVersion":"12","vendor":"unknown","accelerometer":"0.10001241x9.800007x0.1999938","sdRemain":119363,"buildTags":"release-keys","packageName":"com.mihoyo.hyperion","networkType":"WiFi","oaid":"${oaid}","debugStatus":0,"ramCapacity":"127991","magnetometer":"15.625x-28.25x-32.625","display":"${randomDevice.model}","appInstallTimeDiff":1733055335683,"packageVersion":"2.35.0","gyroscope":"0.0x0.0x0.0","batteryStatus":99,"hasKeyboard":1,"board":"${randomDevice.board}"}`,
          platform: '2',
          seed_id: deviceGuid,
          seed_time: new Date().getTime() + '',
        })
      })
      
      if (!fpResponse.ok) {
        return MysFp.generateFallbackFp()
      }
      
      return await fpResponse.json()
    } catch (error) {
      logger.error('生成默认设备指纹失败:', error)
      return MysFp.generateFallbackFp()
    }
  }

  // 生成备用设备指纹（当API调用失败时使用）
  static generateFallbackFp() {
    return {
      data: {
        device_fp: MysFp.getSeed_id(13),
        device_id: MysFp.getSeed_id(16)
      }
    }
  }

  // 生成随机OAID
  static generateOaid() {
    const chars = '0123456789abcdef'
    let result = ''
    const pattern = [8, 4, 4, 4, 12]
    
    for (let i = 0; i < pattern.length; i++) {
      if (i > 0) result += '-'
      for (let j = 0; j < pattern[i]; j++) {
        result += chars[Math.floor(Math.random() * chars.length)]
      }
    }
    return result
  }

  // 生成设备GUID
  static getDeviceGuid() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
  }

  // 生成种子ID
  static getSeed_id(length = 16) {
    const characters = '0123456789abcdef'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += characters[Math.floor(Math.random() * characters.length)]
    }
    return result
  }
}

BaseModel.initDB(MysFp, COLUMNS)
await MysFp.sync()

export default MysFp




